// Ninf-G-XX, ver. 0.1
// Copyright 2011 National Institute of Advanced Industrial Science and Technology
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
 * ByteArrayInputStream.cpp
 *
 *  Created on: Jan 29, 2009
 *      Author: nakada
 */

#include <string.h>
#include "ByteArrayInputStream.hpp"

namespace ninf {

namespace lib {

ByteArrayInputStream::ByteArrayInputStream(const char * array, int size):
  array(array), current(0), size(size){}

/**
 * does nothing. array have to be deallocated by the caller
 */

ByteArrayInputStream::~ByteArrayInputStream() {

}

/**
 * read a single byte
 * if it encounters EOF returns -1
 * if it encounters some error throws exception
 */
int ByteArrayInputStream::read(){
  if (current + 1 > size)
    return -1;
  return 0xff & *(array + current++);
}

/*
 * read byte array and stores it to val
 * it returns number of actually read bytes
 */
#define min(A, B) (A > B? B: A)

int ByteArrayInputStream::read(char * val, int offset, int len){
  int to_copy = min(size - current, len);
  if (to_copy <= 0)
       return 0;
    memcpy(val + offset, array + current, to_copy);
    current += to_copy;
    return to_copy;
}

/*
 * read byte array and stores it to val
 * keep tring to read specified length
 * returns non 0 if succuess, 0 if failed
 */
int ByteArrayInputStream::readFully(char * val, int offset, int len){
  if (size - current < len)
    return 0;
  return read(val, offset, len);
}

/*
 * close underlying stream
 */
void ByteArrayInputStream::close(){
  // do nothing
}


}

}
